package com.secsbrain.development.web.controller;

import com.secsbrain.cmdb.client.iface.AppInfoService;
import com.secsbrain.cmdb.client.iface.OpsInfoService;
import com.secsbrain.common.ResponseResult;
import com.secsbrain.common.ResponseVo;
import com.secsbrain.cmdb.client.model.AppDetail;
import com.secsbrain.cmdb.client.model.Server;
import com.secsbrain.development.biz.IDeployApprovalService;
import com.secsbrain.development.web.dto.MessageDTO;
import com.secsbrain.engine.client.iface.TaskInfoService;
import com.secsbrain.sso.core.SsoHelper;
import com.secsbrain.sso.model.dto.system.UserDetailDTO;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping("api/common")
@ApiIgnore
public class CommonController {
	
    private static final Logger logger = LoggerFactory.getLogger(CommonController.class);
	
	@Autowired
	AppInfoService appInfoService;

	@Autowired
	OpsInfoService opsInfoService;
	
	@Autowired
	TaskInfoService taskInfoService;
	
	@Autowired
    IDeployApprovalService deployApprovalService;

    @RequestMapping(value = "message", method = RequestMethod.GET)
    public ResponseResult message(HttpServletRequest httpServletRequest) {
        List<MessageDTO> messageDTOList = new ArrayList<MessageDTO>();
        
		UserDetailDTO userDetailDTO= SsoHelper.currentUser();
		String token=httpServletRequest.getHeader("token");
		Assert.notNull(userDetailDTO, "没有获取到用户信息，token:"+token);
		
		String roleCode="dev_develop";
		if(!CollectionUtils.isEmpty(userDetailDTO.getUserRoleList())){
			roleCode=userDetailDTO.getUserRoleList().get(0).getCode();
    	}
		
//		ResponseVo<List<TaskDto>> taskListVo=taskInfoService.queryTodo(userDetailDTO.getId()+"",
//				roleCode,ProcessKeyConstant.DEPLOY_KEY);
//
//		if(!taskListVo.isSuccess()){
//			logger.debug("查询待办任务列表失败："+taskListVo.getMsg());
//			return new ResponseResult<>(ErrorCodeEnum.ERROR_COMMON_CHECK.getCode(),taskListVo.getMsg());
//		}
//
//		List<TaskDto> taskList=taskListVo.getData();
//		for(TaskDto taskDto:taskList){
//			DeployApproval deployApprovalParam=new DeployApproval();
//			deployApprovalParam.setProcessInstanceId(taskDto.getProcessInstanceId());
//			DeployApproval deployApproval=deployApprovalService.selectOne(deployApprovalParam);
//			if(deployApproval==null){
//				continue;
//			}
//			ResponseVo<AppDetail> appVo=opsInfoService.queryAppDetailById(deployApproval.getAppId());
//
//			MessageDTO messageDTO=new MessageDTO();
//	        messageDTO.setDate(DateTimeUtils.dateParseString(taskDto.getCreateTime()));
//	        messageDTO.setFrom(taskDto.getName());
//	        messageDTO.setTitle("应用："+appVo.getData().getName()+"，环境："
//	        		+deployApproval.getEnv()+"，分支："+deployApproval.getBranch()+"的发布申请");
//	        messageDTO.setProjectId(deployApproval.getId());
//			messageDTOList.add(messageDTO);
//		}
		return new ResponseResult<>(messageDTOList);
    }
    
    @RequestMapping(value = "envs", method = RequestMethod.GET)
    public ResponseResult envList() {
    	ResponseVo<List<String>> envVo=opsInfoService.queryEnvList();
    	if(!envVo.isSuccess()){
			return new ResponseResult<>(envVo.getErrorCode(),envVo.getMsg());
    	}
		return new ResponseResult<>(envVo.getData());
    }
    
    @RequestMapping(value = "appEnvs/{appId}", method = RequestMethod.GET)
    public ResponseResult appEnvList(@PathVariable("appId") long appId) {
    	Assert.notNull(appId, "应用ID不能为空");
		ResponseVo<AppDetail> appDetailVo=appInfoService.queryAppDetailById(appId);
		if(!appDetailVo.isSuccess()||appDetailVo.getData()==null){
			return new ResponseResult<>(appDetailVo.getErrorCode(),appDetailVo.getMsg());
		}
		AppDetail appDetail=appDetailVo.getData();
		List<Server> serverList=appDetail.getServerList();
		Set<String> envSet=new HashSet<String>();
		for(Server server:serverList){
			envSet.add(server.getEnvName());
		}
		return new ResponseResult<>(envSet);
    }
    
    @RequestMapping(value = "envsFlag", method = RequestMethod.GET)
    public ResponseResult envListFlag(String flag) {
		ResponseVo<List<String>> envVo=opsInfoService.queryEnvListByFlag(flag);
    	if(!envVo.isSuccess()){
			return new ResponseResult<>(envVo.getErrorCode(),envVo.getMsg());
    	}
		return new ResponseResult<>(envVo.getData());
    }

}
